package org.example.order.service.impl;

import org.example.order.service.CoverFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@Service
public class CoverFileServiceImpl implements CoverFileService {

    public static final String COVER_DIR = System.getProperty("user.dir") + "/src/main/resources/upload/cover/";
    public static final String TMP_COVER_DIR = COVER_DIR + "tmp/";

    @Override
    public String upload(MultipartFile file) throws IOException {
        File tmpCoverDir = new File(TMP_COVER_DIR);
        String fileName = randomFileName(Objects.requireNonNull(file.getOriginalFilename()));
        File uploadFile = new File(TMP_COVER_DIR + fileName);
        if (!tmpCoverDir.exists() && !tmpCoverDir.mkdirs()) {
            throw new IOException("创建临时封面目录失败");
        }
        file.transferTo(uploadFile);
        return fileName;
    }

    @Override
    public boolean validate(String filename) throws IOException {
        File coverDir = new File(COVER_DIR);
        File file = new File(TMP_COVER_DIR + filename);
        if (!coverDir.exists() && !coverDir.mkdirs()) {
            throw new IOException("创建封面目录失败");
        }
        return file.renameTo(new File(COVER_DIR + filename));
    }

    @Override
    public boolean delete(String name) {
        File file = new File(COVER_DIR + name);
        return file.delete();
    }

    private String randomFileName(String filename) {
        String uuid = UUID.randomUUID().toString().split("-")[0];
        return uuid + filename.substring(filename.lastIndexOf("."));
    }
}
